package com.hkts.naturalgas.dictionaries.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.hkts.naturalgas.association.service.IHktsRequestAddressAssociationService;
import com.hkts.naturalgas.curvesettings.entity.Curve;
import com.hkts.naturalgas.curvesettings.entity.CurveSettings;
import com.hkts.naturalgas.curvesettings.entity.CurveState;
import com.hkts.naturalgas.curvesettings.mapper.CurveMapper;
import com.hkts.naturalgas.curvesettings.mapper.CurveSettingsMapper;
import com.hkts.naturalgas.curvesettings.mapper.CurveStateMapper;
import com.hkts.naturalgas.curvesettings.service.ICurveService;
import com.hkts.naturalgas.curvesettings.service.ICurveSettingsService;
import com.hkts.naturalgas.curvesettings.service.ICurveStateService;
import com.hkts.naturalgas.datahandler.constance.EnviromentConstance;
import com.hkts.naturalgas.datahandler.constance.EnviromentCurveStateConstance;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionDictionaries;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionItem;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentTemperature;
import com.hkts.naturalgas.dictionaries.entity.HktsFieldControl;
import com.hkts.naturalgas.dictionaries.mapper.HktsEnvironmentProtectionDictionariesMapper;
import com.hkts.naturalgas.dictionaries.mapper.HktsEnvironmentProtectionItemMapper;
import com.hkts.naturalgas.dictionaries.mapper.HktsEnvironmentTemperatureMapper;
import com.hkts.naturalgas.dictionaries.mapper.HktsFieldControlMapper;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionDictionariesService;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionItemService;
import com.hkts.naturalgas.dictionaries.utils.DBUtils;
import com.hkts.naturalgas.dictionaries.vo.PageVo;
import com.hkts.naturalgas.utils.CustomPage;
import com.hkts.naturalgas.utils.HttpAPIService;
import com.hkts.naturalgas.utils.Result;
import com.hkts.naturalgas.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2021-06-23
 */
@Slf4j
@Service
@Transactional
public class HktsEnvironmentProtectionItemServiceImpl extends ServiceImpl<HktsEnvironmentProtectionItemMapper, HktsEnvironmentProtectionItem> implements IHktsEnvironmentProtectionItemService {

    @Autowired
    private DBUtils dBUtils;
    @Autowired
    private HktsEnvironmentProtectionItemMapper hktsEnvironmentProtectionItemMapper;
    @Autowired
    private HktsEnvironmentProtectionDictionariesMapper hktsEnvironmentProtectionDictionariesMapper;
    @Autowired
    private CurveMapper curveMapper;
    @Autowired
    private CurveSettingsMapper curveSettingsMapper;
    @Autowired
    private CurveStateMapper curveStateMapper;

    @Autowired
    private HktsEnvironmentTemperatureMapper hktsEnvironmentTemperatureMapper;
    @Autowired
    public IHktsEnvironmentProtectionDictionariesService iHktsEnvironmentProtectionDictionariesService;
    @Autowired
    public ICurveService iCurveService;
    @Autowired
    public ICurveSettingsService iCurveSettingsService;
    @Autowired
    public ICurveStateService iCurveStateService;
    @Resource
    private HttpAPIService httpAPIService;
    @Autowired
    public IHktsRequestAddressAssociationService iHktsRequestAddressAssociationService;
    @Autowired
    private HktsFieldControlMapper hktsFieldControlMapper;

    @Override
    public IPage<HktsEnvironmentProtectionItem> selectPage(Page<HktsEnvironmentProtectionItem> page, HktsEnvironmentProtectionItem hktsEnvironmentProtectionItem) throws Exception {
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getTableId, hktsEnvironmentProtectionItem.getTableId());
        query.lambda().ne(HktsEnvironmentProtectionItem::getSetType, EnviromentConstance.FORBID_SET);
        query.lambda().ne(HktsEnvironmentProtectionItem::getFieldName, "time");
        Page<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItemPage = hktsEnvironmentProtectionItemMapper.selectPage(page, query);
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = hktsEnvironmentProtectionDictionariesMapper.selectById(hktsEnvironmentProtectionItem.getTableId());
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
        //真实值
        if (hktsEnvironmentProtectionDictionaries.getIsHttp().equals(EnviromentConstance.IS_HTTP)) {
            String s = httpAPIService.doGet("http://192.168.99.67:5000//biz");
            Gson gson = new Gson();
            Map map = new HashMap();
            map = gson.fromJson(s, map.getClass());
            Map data = (Map) map.get("data");
            for (int i = 0; i < hktsEnvironmentProtectionItemPage.getRecords().size(); i++) {
                if (data.get(hktsEnvironmentProtectionItemPage.getRecords().get(i).getCorrespondingField()) != null) {
                    float value = Float.parseFloat(data.get(hktsEnvironmentProtectionItemPage.getRecords()
                            .get(i).getCorrespondingField()).toString());
                    hktsEnvironmentProtectionItemPage.getRecords().get(i).setRealValue(df.format(value));
                }
            }
        } else {
            List<HktsEnvironmentProtectionItem> tableItemByTableId = hktsEnvironmentProtectionItemPage.getRecords();
            List<String> list = new ArrayList<>();
            List<String> listFiled = new ArrayList<>();
            for (int j = 0; j < tableItemByTableId.size(); j++) {
                if (!tableItemByTableId.get(j).getDataType().equals(EnviromentConstance.DATE_TIME)) {
                    list.add(tableItemByTableId.get(j).getFieldName());
                    listFiled.add(tableItemByTableId.get(j).getCorrespondingField());
                }
            }
            try {
                Map<String, Object> associations = iHktsRequestAddressAssociationService.getAssociations(hktsEnvironmentProtectionDictionaries, list, listFiled);
                log.info("真实值{}",associations);
                if (associations.get("code").toString().equals("200")) {
                    //保存数据逻辑
                    for (int i = 0; i < hktsEnvironmentProtectionItemPage.getRecords().size(); i++) {
                        hktsEnvironmentProtectionItemPage.getRecords().get(i).setRealValue(associations.get(hktsEnvironmentProtectionItemPage.getRecords().get(i).getFieldName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //设定值
        List<String> setList = new ArrayList<String>();
        for (int i = 0; i < hktsEnvironmentProtectionItemPage.getRecords().size(); i++) {
            if (!hktsEnvironmentProtectionItemPage.getRecords().get(i).getNeedDeal().equals(EnviromentConstance.NOT_DEAL_WITH)) {
                setList.add(hktsEnvironmentProtectionItemPage.getRecords().get(i).getId());
            }
        }
        if (setList.size() > 0) {
            QueryWrapper<HktsFieldControl> queryFieldControl = Wrappers.query();
            queryFieldControl.lambda().in(HktsFieldControl::getItemId, setList);
            List<HktsFieldControl> hktsFieldControls = hktsFieldControlMapper.selectList(queryFieldControl);
            Map<String, HktsFieldControl> map = hktsFieldControls.stream().collect(Collectors.toMap(HktsFieldControl::getItemId, Function.identity()));
            for (int i = 0; i < hktsEnvironmentProtectionItemPage.getRecords().size(); i++) {
                if (map.containsKey(hktsEnvironmentProtectionItemPage.getRecords().get(i).getId())) {
                    if (hktsEnvironmentProtectionItemPage.getRecords().get(i).getNeedDeal().equals(EnviromentConstance.FIXED_VALUE)) {
                        hktsEnvironmentProtectionItemPage.getRecords().get(i).setSetValue(map.get(hktsEnvironmentProtectionItemPage.getRecords().get(i).getId()).getFixedValue());
                    } else if (hktsEnvironmentProtectionItemPage.getRecords().get(i).getNeedDeal().equals(EnviromentConstance.SECTION)) {
                        hktsEnvironmentProtectionItemPage.getRecords().get(i).setMaxValue(map.get(hktsEnvironmentProtectionItemPage.getRecords().get(i).getId()).getMaxValue());
                        hktsEnvironmentProtectionItemPage.getRecords().get(i).setMinValue(map.get(hktsEnvironmentProtectionItemPage.getRecords().get(i).getId()).getMinValue());
                    }
                }
            }
        }
        return hktsEnvironmentProtectionItemPage;
    }


    @Override
    public List<HktsEnvironmentProtectionItem> selectList(HktsEnvironmentProtectionItem hktsEnvironmentProtectionItem) {
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        QueryWrapper<HktsEnvironmentProtectionItem> entityWrapper = getEntityWrapper(query, hktsEnvironmentProtectionItem);
        entityWrapper.orderByAsc(HktsEnvironmentProtectionItem.FILED_ORDER);
        return hktsEnvironmentProtectionItemMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsEnvironmentProtectionItem> getEntityWrapper(QueryWrapper<HktsEnvironmentProtectionItem> entityWrapper, HktsEnvironmentProtectionItem hktsEnvironmentProtectionItem) {
        //条件拼接
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getFiledDescribe())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.FILED_DESCRIBE, hktsEnvironmentProtectionItem.getFiledDescribe());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getFieldName())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.FIELD_NAME, hktsEnvironmentProtectionItem.getFieldName());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getDataType())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.DATA_TYPE, hktsEnvironmentProtectionItem.getDataType());
        }

        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getCorrespondingField())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.CORRESPONDING_FIELD, hktsEnvironmentProtectionItem.getCorrespondingField());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getIsExport())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.IS_EXPORT, hktsEnvironmentProtectionItem.getIsExport());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getIsDefault())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.IS_DEFAULT, hktsEnvironmentProtectionItem.getIsDefault());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getIsShow())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.IS_SHOW, hktsEnvironmentProtectionItem.getIsShow());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getIsEnable())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.IS_ENABLE, hktsEnvironmentProtectionItem.getIsEnable());
        }
        if (StringUtils.isNotBlank(hktsEnvironmentProtectionItem.getTableId())) {
            entityWrapper.eq(HktsEnvironmentProtectionItem.TABLE_ID, hktsEnvironmentProtectionItem.getTableId());
        }
        return entityWrapper;
    }

    @Override
    public List<HktsEnvironmentProtectionItem> getTableItemByTableId(String tableId) {
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getTableId, tableId);
        query.lambda().eq(HktsEnvironmentProtectionItem::getIsEnable, EnviromentConstance.IS_ENABLE);
        query.lambda().orderByAsc(HktsEnvironmentProtectionItem::getFiledOrder);
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = hktsEnvironmentProtectionItemMapper.selectList(query);
        return hktsEnvironmentProtectionItems;
    }

    @Override
    public CustomPage getPage(PageVo vo) throws ParseException {
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = hktsEnvironmentProtectionDictionariesMapper.selectById(vo.getTableId());

        CustomPage page = new CustomPage();
        //分页
        Integer count = dBUtils.getCount(vo, hktsEnvironmentProtectionDictionaries.getTableName());
        List<Map<String, Object>> pageResult = dBUtils.getPageResult(vo, hktsEnvironmentProtectionDictionaries.getTableName());
        page.setTotalRows((long) count);
        page.setPageSize((long) vo.getPageSize());
        page.setPageNumber((long) vo.getPageNumber());
        page.setResultData(pageResult);
        return page;
    }

    @Override
    public Map getChart(PageVo vo) throws ParseException {
        vo.setTimeInterval("%00");
        Map<String, Object> result = new HashMap<String, Object>();
        List<HktsEnvironmentProtectionItem> tableItemByTableId = this.getTableItemByTableId(vo.getTableId());
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = hktsEnvironmentProtectionDictionariesMapper.selectById(vo.getTableId());
        CustomPage page = new CustomPage();
        //分页
        Integer count = dBUtils.getCount(vo, hktsEnvironmentProtectionDictionaries.getTableName());
        List<Map<String, Object>> pageResult = dBUtils.getPageResult(vo, hktsEnvironmentProtectionDictionaries.getTableName(), tableItemByTableId);
        Map<String, List<Float>> map = new HashMap<String, List<Float>>();
        List<String> fildList = new ArrayList<String>();
        for (int i = 0; i < tableItemByTableId.size(); i++) {
            String fieldName = tableItemByTableId.get(i).getFieldName();
            if (!tableItemByTableId.get(i).getDataType().equals("datetime")) {
                List<Float> strList = new ArrayList<>();
                for (int j = 0; j < pageResult.size(); j++) {
                    strList.add(pageResult.get(j).get(fieldName) == null ? 0 : Float.parseFloat(pageResult.get(j).get(fieldName).toString()));
                }
                map.put(tableItemByTableId.get(i).getFiledDescribe(), strList);
                fildList.add(tableItemByTableId.get(i).getFiledDescribe());
            } else {
                List<String> strList = pageResult.stream().map(p -> p.get(fieldName).toString()).collect(Collectors.toList());
                result.put("times", strList);
            }
        }
        result.put("records", map);
        result.put("list", fildList);
        result.put("totalRows", count);
        result.put("pageSize", vo.getPageSize());
        result.put("pageNumber", vo.getPageNumber());
        return result;
    }

    @Override
    public Result<Object> getListData(String tableId) throws ParseException {
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = hktsEnvironmentProtectionDictionariesMapper.selectById(tableId);
        QueryWrapper<CurveState> stateQueryWrapper = Wrappers.query();
        stateQueryWrapper.lambda().eq(CurveState::getWorkShopId, hktsEnvironmentProtectionDictionaries.getWorkShop());
        CurveState curveState = curveStateMapper.selectOne(stateQueryWrapper);
        HktsEnvironmentProtectionItem item = new HktsEnvironmentProtectionItem();
        item.setTableId(tableId);
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = selectList(item);

        List<Map<String, Object>> list = dBUtils.getWdAndGlList(hktsEnvironmentProtectionDictionaries, hktsEnvironmentProtectionItems);


        List<HktsEnvironmentProtectionItem> totle = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Set<Map.Entry<String, Object>> entries = list.get(i).entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
                query.lambda().eq(HktsEnvironmentProtectionItem::getFieldName, entry.getKey()).eq(HktsEnvironmentProtectionItem::getTableId, tableId);
                HktsEnvironmentProtectionItem hktsEnvironmentProtectionItem = hktsEnvironmentProtectionItemMapper.selectOne(query);


                if (hktsEnvironmentProtectionItem.getDescribeId() == 1) {
                    if (entry.getValue() != null) {
                        hktsEnvironmentProtectionItem.setWd(entry.getValue().toString());
                    } else {
                        hktsEnvironmentProtectionItem.setWd("0");
                    }

                } else if (hktsEnvironmentProtectionItem.getDescribeId() == 5) {
                    if (entry.getValue() != null) {
                        hktsEnvironmentProtectionItem.setTime(entry.getValue().toString());
                    } else {
                        hktsEnvironmentProtectionItem.setTime("");
                    }
                } else if (hktsEnvironmentProtectionItem.getDescribeId() == 2 || hktsEnvironmentProtectionItem.getDescribeId() == 3) {
                    if (entry.getValue() != null) {
                        hktsEnvironmentProtectionItem.setGl(entry.getValue().toString());
                    } else {
                        hktsEnvironmentProtectionItem.setGl("0");
                    }
                }
                totle.add(hktsEnvironmentProtectionItem);
            }
        }

        Collections.sort(totle, new Comparator<HktsEnvironmentProtectionItem>() {
            @Override
            public int compare(HktsEnvironmentProtectionItem o1, HktsEnvironmentProtectionItem o2) {
                //升序
                return o1.getFiledOrder().compareTo(o2.getFiledOrder());
            }
        });

        List<HktsEnvironmentProtectionItem> gls = new ArrayList<>();

        List<HktsEnvironmentProtectionItem> wds = new ArrayList<>();

        List<HktsEnvironmentProtectionItem> time = new ArrayList<>();

        List<HktsEnvironmentProtectionItem> other = new ArrayList<>();
        for (int i = 0; i < totle.size(); i++) {

            if (totle.get(i).getDescribeId() == 1) {
                wds.add(totle.get(i));
            } else if (totle.get(i).getDescribeId() == 2 || totle.get(i).getDescribeId() == 3) {
                gls.add(totle.get(i));
            } else if (totle.get(i).getDescribeId() == 5) {
                time.add(totle.get(i));
            } else if (totle.get(i).getDescribeId() == 4) {
                other.add(totle.get(i));
            }
        }
        //温度/功率
        List<Object> tAndO = new ArrayList<>();
        for (int i = 0; i < wds.size(); i++) {
            Map<String, Object> all = new HashMap<>();

            all.put("temperature", wds.get(i).getWd());
            if (gls.size() > 0) {
                all.put("opening", gls.get(i).getGl());
            } else {
                all.put("opening", "0");
            }

            tAndO.add(all);
        }
        //s时间
        List<Object> times = new ArrayList<>();
        for (int i = 0; i < time.size(); i++) {
            Map<String, Object> all = new HashMap<>();

            all.put("time", time.get(i).getTime());
            times.add(all);
        }

        //其他
        List<Object> others = new ArrayList<>();
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getDescribeId, 4).eq(HktsEnvironmentProtectionItem::getTableId, tableId);
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItemsByDescribeId = hktsEnvironmentProtectionItemMapper.selectList(query);
        for (int i = 0; i < hktsEnvironmentProtectionItemsByDescribeId.size(); i++) {
            Map<String, Object> all = new HashMap<>();
            if (other.size() > 0) {
                all.put(hktsEnvironmentProtectionItemsByDescribeId.get(i).getFieldName(), other.get(i).getOther());
            } else {
                all.put(hktsEnvironmentProtectionItemsByDescribeId.get(i).getFieldName(), "0");
            }

            others.add(all);
        }

        //所有
        Map<String, Object> allResult = new HashMap<>();

        if (tAndO.size() > 0) {
            allResult.put("tAndO", tAndO);
        } else {
            QueryWrapper<HktsEnvironmentProtectionItem> queryByDescribeIdOne = Wrappers.query();
            queryByDescribeIdOne.lambda().eq(HktsEnvironmentProtectionItem::getTableId, tableId).eq(HktsEnvironmentProtectionItem::getDescribeId, 1);
/*
                    wrapper -> wrapper.eq(HktsEnvironmentProtectionItem::getDescribeId,1).or().eq(HktsEnvironmentProtectionItem::getDescribeId,3));
*/
            List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItemsByDescribeIdOne = hktsEnvironmentProtectionItemMapper.selectList(queryByDescribeIdOne);
            for (int i = 0; i < hktsEnvironmentProtectionItemsByDescribeIdOne.size(); i++) {
                Map<String, Object> all = new HashMap<>();
                all.put("temperature", "0");
                all.put("opening", "0");
                tAndO.add(all);
            }
            allResult.put("tAndO", tAndO);
        }
        if (times.size() > 0) {
            allResult.put("time", times);
        } else {
            allResult.put("time", "0");
        }

        if (others.size() > 0) {
            allResult.put("other", others);
        } else {
            for (int i = 0; i < hktsEnvironmentProtectionItemsByDescribeId.size(); i++) {
                Map<String, Object> all = new HashMap<>();
                all.put(hktsEnvironmentProtectionItemsByDescribeId.get(i).getFieldName(), "0");
                others.add(all);
            }
            allResult.put("other", others);
        }

        allResult.put("tableId", tableId);

        Curve curve = curveMapper.selectById(tableId);
        allResult.put("heatNumber", curve.getHeatNumber());

        QueryWrapper<CurveSettings> curveSettingsQueryWrapper = Wrappers.query();
        curveSettingsQueryWrapper.lambda().eq(CurveSettings::getCurveId, curve.getId());
        curveSettingsQueryWrapper.lambda().eq(CurveSettings::getCurveId, curve.getId()).ne(CurveSettings::getIsHidden, 1);
        List<CurveSettings> curveSettings = curveSettingsMapper.selectList(curveSettingsQueryWrapper);
        QueryWrapper<CurveSettings> curveSettingsQuery = Wrappers.query();
        curveSettingsQuery.lambda().eq(CurveSettings::getCurveId, curve.getId()).eq(CurveSettings::getCurrentNode, "1");
        CurveSettings curveSettingsByCurrentNode = curveSettingsMapper.selectOne(curveSettingsQuery);

        Integer runTime = 0;

        for (int i = 0; i < curveSettings.size(); i++) {
            if (curveSettings.get(i).getOrderBy() < curveSettingsByCurrentNode.getOrderBy()) {
                runTime = curveSettings.get(i).getTotalSeconds() + runTime;
            }
        }
        double runTimeT=0;
        if(curveSettingsByCurrentNode.getIsHidden().equals("1")){
            runTimeT = runTime;
        }else{
            runTimeT = new BigDecimal((float) (runTime + curveSettingsByCurrentNode.getCurrentSeconds()) / 3600).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();

        }
       //已运行时间
        QueryWrapper<HktsEnvironmentTemperature> temperatureQueryWrapper = Wrappers.query();
        temperatureQueryWrapper.lambda().eq(HktsEnvironmentTemperature::getTableId, tableId);
        HktsEnvironmentTemperature hktsEnvironmentTemperature = hktsEnvironmentTemperatureMapper.selectOne(temperatureQueryWrapper);
        Integer curveStateValue = Integer.valueOf(curveState.getSystemCurveState());

        if (curveStateValue == 4 && hktsEnvironmentTemperature.getRunTimeHour() != null) {
            double runTimeOne = new BigDecimal(hktsEnvironmentTemperature.getRunTimeHour()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            Float runTimeMinute = hktsEnvironmentTemperature.getRunTimeMinute();
            double runT = new BigDecimal(runTimeMinute / 60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            runT = runT + runTimeOne;
            BigDecimal bg = new BigDecimal(runT);
            runT = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            allResult.put("runTime", runT);
        } else {
            allResult.put("runTime", runTimeT);
        }

        Float all = 0.0f;

        List<Integer> orderMax = new ArrayList<>();
        List<Float> collect = curveSettings.stream().map(CurveSettings::getTimePoint).collect(Collectors.toList());
        all = Collections.max(collect);
        double allTime = new BigDecimal(all).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();

        double residueTime = allTime - runTimeT;
        BigDecimal bg = new BigDecimal(residueTime);
        residueTime = bg.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
        BigDecimal rt = new BigDecimal(runTimeT);
        BigDecimal tt = new BigDecimal(allTime);

        if (curveStateValue == 4 && hktsEnvironmentTemperature.getRemainingTimeHour() != null) {
            double runRemaTimeOne = new BigDecimal(hktsEnvironmentTemperature.getRemainingTimeHour()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            Float remainingTimeMinute = hktsEnvironmentTemperature.getRemainingTimeMinute();
            double runTM = new BigDecimal(remainingTimeMinute / 60).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            runTM = runTM + runRemaTimeOne;

            BigDecimal bgRunTM = new BigDecimal(runTM);
            runTM = bgRunTM.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            allResult.put("residueTime", runTM);
        } else if (rt.compareTo(tt) == 1) {
            allResult.put("residueTime", 0);
        } else {
            allResult.put("residueTime", residueTime);
        }
        allResult.put("totalTime", all);

        HktsEnvironmentTemperature hktsEnvironmentTemperatureT = hktsEnvironmentTemperatureMapper.selectById(tableId);
        allResult.put("settingTemperature", hktsEnvironmentTemperatureT.getSettingTemperature());
        return ResultUtil.data(allResult);
    }


    @Override
    public Map<String, List<HktsEnvironmentProtectionItem>> getItemMap(List<HktsEnvironmentProtectionDictionaries> hktsEnvironmentProtectionDictionaries1) {
        Map<String, List<HktsEnvironmentProtectionItem>> map = new HashMap<String, List<HktsEnvironmentProtectionItem>>();
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getIsEnable, EnviromentConstance.IS_ENABLE);
        query.lambda().orderByAsc(HktsEnvironmentProtectionItem::getFiledOrder);
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = hktsEnvironmentProtectionItemMapper.selectList(query);
        for (int i = 0; i < hktsEnvironmentProtectionDictionaries1.size(); i++) {
            HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = hktsEnvironmentProtectionDictionaries1.get(i);
            map.put(hktsEnvironmentProtectionDictionaries.getId(), hktsEnvironmentProtectionItems.stream().filter(hktsEnvironmentProtectionItem ->
                    hktsEnvironmentProtectionDictionaries.getId().equals(hktsEnvironmentProtectionItem.getTableId())).collect(Collectors.toList()));
        }
        return map;
    }

    /**
     * 功能描述:
     * 获取市局数据接口
     *
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @Author: 杨春科
     * @Date: 2021-11-03 14:54
     * @Description //TODO
     */
    @Override
    public Map<String, Object> testDataInterface() throws ParseException {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<HktsEnvironmentProtectionDictionaries> queryHktsEnvironmentProtectionDictionaries = Wrappers.query();
        queryHktsEnvironmentProtectionDictionaries.lambda().eq(HktsEnvironmentProtectionDictionaries::getIsEnable, EnviromentConstance.IS_ENABLE);
        List<HktsEnvironmentProtectionDictionaries> hktsEnvironmentProtectionDictionaries =
                hktsEnvironmentProtectionDictionariesMapper.selectList(queryHktsEnvironmentProtectionDictionaries);
        QueryWrapper<CurveState> queryCurveState = Wrappers.query();
        List<CurveState> curveStates = curveStateMapper.selectList(queryCurveState);
        Map<String, String> maps = curveStates.stream().collect(Collectors.toMap(CurveState::getWorkShopId, CurveState::getSystemCurveState, (key1, key2) -> key2));
        for (int i = 0; i < hktsEnvironmentProtectionDictionaries.size(); i++) {
            if (maps.get(hktsEnvironmentProtectionDictionaries.get(i).getWorkShop()) == null || !maps.get(hktsEnvironmentProtectionDictionaries.get(i).getWorkShop()).equals(EnviromentCurveStateConstance.SHUT_DOWN)) {
                Map<String, Object> lastRow = dBUtils.getLastRow(hktsEnvironmentProtectionDictionaries.get(i).getTableName());
                if (lastRow != null) {
                    result.putAll(lastRow);
                }
            }
        }
        return result;
    }

    public float getValue(Object value) {
        if (value != null && !value.toString().equals("null")) {
            return Float.parseFloat(value.toString());
        } else {
            return 0;
        }
    }

    public BigInteger getIntValue(Object value) {
        if (value != null && !value.toString().equals("null")) {
            BigInteger db_1_fwd = new BigInteger(value.toString());
            return db_1_fwd;
        } else {
            BigInteger db_1_fwd = new BigInteger("0");
            return db_1_fwd;
        }
    }

    @Override
    public Map<String, Object> testPowerDataInterface() throws ParseException {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, Object> bSPeiDian = dBUtils.getLastRow("beishao1peidianshi");
        if (bSPeiDian != null) {
            result.put("db_1_fwd", getIntValue(bSPeiDian.get("db_1_fwd")));
            result.put("db_2_fwd", getIntValue(bSPeiDian.get("db_2_fwd")));
            result.put("sb_1_fwd", getValue(bSPeiDian.get("sb_1_fwd")));
            result.put("sb_2_fwd", getValue(bSPeiDian.get("sb_2_fwd")));
            result.put("qb_1_bk", getValue(bSPeiDian.get("qb_1_bk")));
            result.put("qb_2_bk", getIntValue(bSPeiDian.get("qb_2_bk")));
        }
        return result;
    }

    @Override
    public Map<String, Object> testBaijingDataInterface() throws ParseException {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, Object> duanshaojinghua = dBUtils.getLastRow("duanshaojinghua");
        result.put("xhb_1_A", getValue(duanshaojinghua.get("xhb_1_A")));
        result.put("xhb_2_A", getValue(duanshaojinghua.get("xhb_2_A")));
        result.put("xhb_3_A", getValue(duanshaojinghua.get("xhb_3_A")));
        result.put("xhb_4_A", getValue(duanshaojinghua.get("xhb_4_A")));
        Map<String, Object> yandaowendu = dBUtils.getLastRow("yandaowendu");
        result.put("yandao_1_T", getValue(yandaowendu.get("yandao_1_T")));
        result.put("yandao_2_T", getValue(yandaowendu.get("yandao_2_T")));
        result.put("yandao_3_T", getValue(yandaowendu.get("yandao_3_T")));
        result.put("yandao_4_T", getValue(yandaowendu.get("yandao_4_T")));
        Map<String, Object> beishao1peidianshi = dBUtils.getLastRow("beishao1peidianshi");
        result.put("dsgyfj_1_A", getValue(beishao1peidianshi.get("dsgyfj_1_A")));
        result.put("dsgyfj_2_A", getValue(beishao1peidianshi.get("dsgyfj_2_A")));
        Map<String, Object> calcination_other = dBUtils.getLastRow("calcination_other");
        result.put("ds_1sd_2v", getValue(calcination_other.get("ds_1sd_2v")));
        result.put("ds_1sd_2i", getValue(calcination_other.get("ds_1sd_2i")));
        result.put("ds_2sd_2v", getValue(calcination_other.get("ds_2sd_2v")));
        result.put("ds_2sd_2i", getValue(calcination_other.get("ds_2sd_2i")));
        Map<String, Object> calcination_desulfurization_denitration = dBUtils.getLastRow("calcination_desulfurization_denitration");
        result.put("dsjh_tlph", getValue(calcination_desulfurization_denitration.get("dsjh_tlph")));
        result.put("ds1_gjb", getValue(calcination_desulfurization_denitration.get("ds1_gjb")));
        result.put("ds2_gjb", getValue(calcination_desulfurization_denitration.get("ds2_gjb")));
        return result;
    }

    public HktsEnvironmentProtectionItemServiceImpl() {
        super();
    }

    //市环保局
    @Override
    public Map<String, Object> dataInterface() throws ParseException {
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getIsCity, "1");
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = hktsEnvironmentProtectionItemMapper.selectList(query);
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = new HktsEnvironmentProtectionDictionaries();
        hktsEnvironmentProtectionDictionaries.setIsEnable(EnviromentConstance.IS_ENABLE);
        List<HktsEnvironmentProtectionDictionaries> hktsEnvironmentProtectionDictionaries1 = iHktsEnvironmentProtectionDictionariesService.selectList(hktsEnvironmentProtectionDictionaries);
        // Map<String, String> tableMap = hktsEnvironmentProtectionDictionaries1.stream().collect(Collectors.toMap(HktsEnvironmentProtectionDictionaries::getId, HktsEnvironmentProtectionDictionaries::getTableName,(key1 , key2)-> key2 ));
        Map<String, List<CurveSettings>> curveSettingMap = new HashMap<String, List<CurveSettings>>();
        curveSettingMap = iCurveSettingsService.selectMapforShelder(hktsEnvironmentProtectionDictionaries1);
        Map<String, CurveState> stringCurveStateMap = iCurveStateService.curveStateMap();
        Map<String, Object> result = new HashMap<>();
        for (int i = 0; i < hktsEnvironmentProtectionDictionaries1.size(); i++) {
            if (stringCurveStateMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getWorkShop()) != null && stringCurveStateMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getWorkShop()).getSystemCurveState().equals(EnviromentCurveStateConstance.SHUT_DOWN)) {
                continue;
            }
            String id = hktsEnvironmentProtectionDictionaries1.get(i).getId();
            List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionMaps = hktsEnvironmentProtectionItems.stream().filter(HktsEnvironmentProtectionItem -> HktsEnvironmentProtectionItem.getTableId().equals(id)).collect(Collectors.toList());
            if (hktsEnvironmentProtectionMaps.size() > 0) {
                Map<String, Object> lastRow = dBUtils.getLastRow(hktsEnvironmentProtectionDictionaries1.get(i).getTableName());
                for (int j = 0; j < hktsEnvironmentProtectionMaps.size(); j++) {
                    result.put(hktsEnvironmentProtectionMaps.get(j).getFieldName(), lastRow.get(hktsEnvironmentProtectionMaps.get(j).getFieldName()));
                }
                //result.putAll(lastRow);
                //判断是否有曲线 如果有将曲线运行时间剩余时间计算出结果
                if (StringUtils.isNotBlank(hktsEnvironmentProtectionDictionaries1.get(i).getCurveId())) {
                    List<CurveSettings> curveSettings = curveSettingMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getCurveId());
                    int totalSeconds = 0;
                    int runSeconds = 0;
                    for (int j = 0; j < curveSettings.size() - 2; j++) {
                        if (curveSettings.get(j).getCurrentNode().equals(EnviromentConstance.IS_CURRENT_NODE)) {
                            runSeconds = totalSeconds + curveSettings.get(j).getCurrentSeconds();
                        }
                        totalSeconds = totalSeconds + curveSettings.get(j).getTotalSeconds();
                    }
                    //运行时间
                    result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_running_time", (float) runSeconds / 3600);
                    //
                    if (runSeconds < totalSeconds) {
                        result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_remaining_time", (float) (totalSeconds - runSeconds) / 3600);
                    } else {
                        result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_remaining_time", 0);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> powerDataInterface() throws ParseException {
        Map<String, Object> result = new HashMap<String, Object>();

        Map<String, Object> beishao1peidianshi = dBUtils.getLastRow("beishao1peidianshi");
        result.put("db_1_fwd", getIntValue(beishao1peidianshi.get("db_1_fwd")));
        result.put("db_2_fwd", getIntValue(beishao1peidianshi.get("db_2_fwd")));
        result.put("sb_1_fwd", getValue(beishao1peidianshi.get("sb_1_fwd")));
        result.put("sb_2_fwd", getValue(beishao1peidianshi.get("sb_2_fwd")));
        result.put("qb_1_bk", getValue(beishao1peidianshi.get("qb_1_bk")));
        result.put("qb_2_bk", getIntValue(beishao1peidianshi.get("qb_2_bk")));
        return result;
    }

    @Override
    public Map<String, Object> baijingDataInterface() throws ParseException {
        QueryWrapper<HktsEnvironmentProtectionItem> query = Wrappers.query();
        query.lambda().eq(HktsEnvironmentProtectionItem::getIsAtmosphere, "1");
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = hktsEnvironmentProtectionItemMapper.selectList(query);
        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionaries = new HktsEnvironmentProtectionDictionaries();
        hktsEnvironmentProtectionDictionaries.setIsEnable(EnviromentConstance.IS_ENABLE);
        List<HktsEnvironmentProtectionDictionaries> hktsEnvironmentProtectionDictionaries1 = iHktsEnvironmentProtectionDictionariesService.selectList(hktsEnvironmentProtectionDictionaries);
        // Map<String, String> tableMap = hktsEnvironmentProtectionDictionaries1.stream().collect(Collectors.toMap(HktsEnvironmentProtectionDictionaries::getId, HktsEnvironmentProtectionDictionaries::getTableName,(key1 , key2)-> key2 ));
        Map<String, Object> result = new HashMap<>();
        Map<String, List<CurveSettings>> curveSettingMap = new HashMap<String, List<CurveSettings>>();
        curveSettingMap = iCurveSettingsService.selectMapforShelder(hktsEnvironmentProtectionDictionaries1);
        Map<String, CurveState> stringCurveStateMap = iCurveStateService.curveStateMap();

        for (int i = 0; i < hktsEnvironmentProtectionDictionaries1.size(); i++) {
            if (stringCurveStateMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getWorkShop()) != null && stringCurveStateMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getWorkShop()).getSystemCurveState().equals(EnviromentCurveStateConstance.SHUT_DOWN)) {
                continue;
            }
            String id = hktsEnvironmentProtectionDictionaries1.get(i).getId();
            List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionMaps = hktsEnvironmentProtectionItems.stream().filter(HktsEnvironmentProtectionItem -> HktsEnvironmentProtectionItem.getTableId().equals(id)).collect(Collectors.toList());
            if (hktsEnvironmentProtectionMaps.size() > 0) {
                Map<String, Object> lastRow = dBUtils.getLastRow(hktsEnvironmentProtectionDictionaries1.get(i).getTableName());
                for (int j = 0; j < hktsEnvironmentProtectionMaps.size(); j++) {
                    result.put(hktsEnvironmentProtectionMaps.get(j).getFieldName(), lastRow.get(hktsEnvironmentProtectionMaps.get(j).getFieldName()));
                }
                // result.putAll(lastRow);
                //判断是否有曲线 如果有将曲线运行时间剩余时间计算出结果
                if (StringUtils.isNotBlank(hktsEnvironmentProtectionDictionaries1.get(i).getCurveId())) {
                    List<CurveSettings> curveSettings = curveSettingMap.get(hktsEnvironmentProtectionDictionaries1.get(i).getCurveId());
                    int totalSeconds = 0;
                    int runSeconds = 0;
                    for (int j = 0; j < curveSettings.size() - 2; j++) {
                        if (curveSettings.get(j).getCurrentNode().equals(EnviromentConstance.IS_CURRENT_NODE)) {
                            runSeconds = totalSeconds + curveSettings.get(j).getCurrentSeconds();
                        }
                        totalSeconds = totalSeconds + curveSettings.get(j).getTotalSeconds();
                    }
                    //运行时间
                    result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_running_time", (float) runSeconds / 3600);
                    //
                    if (runSeconds < totalSeconds) {
                        result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_remaining_time", (float) (totalSeconds - runSeconds) / 3600);
                    } else {
                        result.put(hktsEnvironmentProtectionDictionaries1.get(i).getTableName() + "_remaining_time", 0);
                    }
                }
            }
        }
        return result;
    }
}
